package jp.ne.iforce.android.jschatest;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.c2dm.C2DMessaging;

import jp.ne.iforce.android.jschatest.R;

public class JschaActivity extends Activity implements Runnable {


    public static String NICKNAME;
    public EditText nickEdit;
    private ProgressDialog progressDialog;

    public String TAG = "JschaActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    	setContentView(R.layout.regist);


    	((Button) findViewById(R.id.Start_button)).setOnClickListener(Start_buttonListener);
    	((Button) findViewById(R.id.Regist_button)).setOnClickListener(Regist_buttonListener);
    	((Button) findViewById(R.id.Receivelist_button)).setOnClickListener(Receivelist_buttonListener);
    	((Button) findViewById(R.id.Stop_button)).setOnClickListener(Stop_buttonListener);

    	((Button) findViewById(R.id.Close_button)).setOnClickListener(Close_buttonListener);

    }






    /**
     * 閉じるボタン
     */
    OnClickListener Close_buttonListener = new View.OnClickListener() {
    	public void onClick(View v) {
    		finish();
    	}

    };

    /**
     * サービス開始
     */
    OnClickListener Start_buttonListener = new View.OnClickListener() {
    	public void onClick(View v) {
    		Log.d(TAG,"Start_buttonListener");
    		startService(new Intent(getBaseContext(),ToastService.class));
    		Toast.makeText(JschaActivity.this, "受信サービスを開始しました", Toast.LENGTH_SHORT).show();
    	}

    };

    /**
     * サービス停止
     */
    OnClickListener Stop_buttonListener = new View.OnClickListener() {
    	public void onClick(View v) {
    		Log.d(TAG,"Stop_buttonListener");
    		stopService(new Intent(getBaseContext(),ToastService.class));
    		Toast.makeText(JschaActivity.this, "受信サービスを停止しました", Toast.LENGTH_SHORT).show();
    	}

    };

    /**
     * 受信メッセージ一覧ボタン
     */
    String[] str_items;
    OnClickListener Receivelist_buttonListener = new View.OnClickListener() {
    	public void onClick(View v) {

    		Log.d(TAG,"Receivelist_buttonListener");

    		CreateProductHelper helper = new CreateProductHelper(JschaActivity.this);
    		SQLiteDatabase db = helper.getWritableDatabase();
    		Cursor cursol = null;

        	try{

        		String selectAll = "SELECT _id,datetime(time, '+9 hours'),fromuser,message FROM t_message ORDER BY time DESC";
        		cursol = db.rawQuery(selectAll, null);

        		int count = cursol.getCount();
        		str_items = new String[count];

        		Log.d(TAG,"count:"+Integer.toString(count));
        		int i = 0;
        		while(cursol.moveToNext()){
        			str_items[i] = cursol.getString(1) + " : " + cursol.getString(2) + "\n" + cursol.getString(3);
        			i++;
        			Log.d("MessageList",cursol.getString(0) + " : " + cursol.getString(1) + " : " + cursol.getString(2) + " : " + cursol.getString(3));
            	}


        	}catch (Exception e) {
        		Log.d("insertList","ERROR!!SELECT FAILED");

        		return;
    		}
        	db.close();



    		// Multi Choice Dialog
        	new AlertDialog.Builder(JschaActivity.this)
        	.setTitle("受信メッセージ一覧")
        	.setItems(str_items, new DialogInterface.OnClickListener(){
        		public void onClick(DialogInterface dialog, int which) {

        		}
        	})
        	.show();
    	}

    };

    /**
     * サーバに登録
     */
    OnClickListener Regist_buttonListener = new View.OnClickListener() {
    	public void onClick(View v) {
    		//ニックネーム入力欄の生成
        	nickEdit = new EditText(JschaActivity.this);
        	nickEdit.setHint("ニックネーム");	//ヒント
        	nickEdit.setLines(1);				//1行
        	nickEdit.setInputType(InputType.TYPE_CLASS_TEXT);	//改行禁止

        	//ダイアログの生成及びリスナー登録
            new AlertDialog.Builder(JschaActivity.this)
            .setTitle("サーバに登録します")	//タイトル設定
            .setView(nickEdit)				//入力欄配置
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {	//OKボタン
            	public void onClick(DialogInterface dialog, int whichButton) {
            		//通信中ダイアログ
            		progressDialog = new ProgressDialog(JschaActivity.this);
    				progressDialog.setMessage("通信中・・・");
    				progressDialog.setIndeterminate(false);
    				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    				progressDialog.show();
    				//スレッド開始
    				Thread thread = new Thread(JschaActivity.this);
    				thread.start();
            	}
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            	public void onClick(DialogInterface dialog, int whichButton) {
            		/* Cancel ボタンをクリックした時の処理 */
            	}
            })
            .show();

    	}

    };


    public void run() {

    	NICKNAME = nickEdit.getText().toString();

    	// C2DMサーバーへ登録
    	C2DMessaging.register(this, "iforce.develop@gmail.com");
    	try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
		handler.sendEmptyMessage(0);
	}

    private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			Toast toast = Toast.makeText(JschaActivity.this, "登録が完了しました", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER | Gravity.CENTER_VERTICAL,0,0);
			toast.show();
		}
	};

}